#import "SMMomentCell.h"
#import "../../Models/SMMoment.h"
#import "../../Models/SMComment.h"
#import "../../Utils/SMTimeAgo.h"
#import <Masonry/Masonry.h>
#import <SDWebImage/UIImageView+WebCache.h>

static const CGFloat kPadding = 12.f;
static const CGFloat kAvatar = 40.f;
static const CGFloat kGridSpacing = 6.f;
static const CGFloat kActionBarH = 36.f;
static const NSInteger kCommentMaxLines = 2;
static const NSInteger kTextMaxLines = 3;

@interface SMMomentCell ()
@property(nonatomic, strong) UIView *card;
@property(nonatomic, strong) UIImageView *avatar;
@property(nonatomic, strong) UILabel *author;
@property(nonatomic, strong) UILabel *timeL;
@property(nonatomic, strong) UILabel *textL;
@property(nonatomic, strong) UIButton *moreBtn;
@property(nonatomic, strong) UIView *grid;
@property(nonatomic, strong) UIButton *likeBtn;
@property(nonatomic, strong) UIButton *cmtBtn;
@property(nonatomic, strong) UILabel *likesCountL;
@property(nonatomic, strong) UIStackView *commentsStack;
@property(nonatomic, strong) UIView *hairline;
@property(nonatomic, copy)   NSString *momentId;

// 折叠相关
@property(nonatomic, assign) BOOL needMoreButton;
@property(nonatomic, strong) NSLayoutConstraint *textMaxHConstraint; // 收起时限制 3 行的“硬约束”
@end

@implementation SMMomentCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = UIColor.systemGroupedBackgroundColor;

        _card = [UIView new];
        _card.backgroundColor = UIColor.secondarySystemBackgroundColor;
        _card.layer.cornerRadius = 12;
        _card.layer.masksToBounds = YES;
        [self.contentView addSubview:_card];
        [_card mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.contentView).insets(UIEdgeInsetsMake(kPadding, kPadding, kPadding, kPadding));
        }];

        _avatar=[UIImageView new];
        _avatar.layer.cornerRadius=kAvatar/2.0; _avatar.clipsToBounds=YES;
        
        // ✅ 允许点击 + 手势
        _avatar.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapAv = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAvatar)];
        [_avatar addGestureRecognizer:tapAv];

        _author=[UILabel new];
        _author.font=[UIFont boldSystemFontOfSize:15];

        _timeL=[UILabel new];
        _timeL.font=[UIFont systemFontOfSize:12];
        _timeL.textColor=UIColor.tertiaryLabelColor;

        _textL=[UILabel new];
        _textL.font=[UIFont systemFontOfSize:15];
        _textL.numberOfLines=0;
        _textL.lineBreakMode = NSLineBreakByTruncatingTail;

        _moreBtn=[UIButton buttonWithType:UIButtonTypeSystem];
        [_moreBtn setTitle:@"展开" forState:UIControlStateNormal];
        _moreBtn.titleLabel.font=[UIFont systemFontOfSize:14];
        [_moreBtn addTarget:self action:@selector(tapMore) forControlEvents:UIControlEventTouchUpInside];

        _grid=[UIView new];

        [_card addSubview:_avatar];
        [_card addSubview:_author];
        [_card addSubview:_timeL];
        [_card addSubview:_textL];
        [_card addSubview:_moreBtn];
        [_card addSubview:_grid];

        [_avatar mas_makeConstraints:^(MASConstraintMaker *make){
            make.top.left.equalTo(self.card).offset(kPadding);
            make.size.mas_equalTo(CGSizeMake(kAvatar, kAvatar));
        }];
        [_author mas_makeConstraints:^(MASConstraintMaker *make){
            make.top.equalTo(self.card).offset(kPadding+2);
            make.left.equalTo(self.avatar.mas_right).offset(8);
            make.right.lessThanOrEqualTo(self.card).offset(-kPadding);
        }];
        [_timeL mas_makeConstraints:^(MASConstraintMaker *make){
            make.top.equalTo(self.author.mas_bottom).offset(2);
            make.left.equalTo(self.author);
        }];
        [_textL mas_makeConstraints:^(MASConstraintMaker *make){
            make.top.equalTo(self.avatar.mas_bottom).offset(8);
            make.left.equalTo(self.card).offset(kPadding);
            make.right.equalTo(self.card).offset(-kPadding);
        }];

        // 收起时的三行“硬约束”，先创建，默认不激活
        self.textMaxHConstraint = [self.textL.heightAnchor constraintLessThanOrEqualToConstant:0];
        self.textMaxHConstraint.active = NO;

        [_moreBtn mas_makeConstraints:^(MASConstraintMaker *make){
            make.top.equalTo(self.textL.mas_bottom).offset(4);
            make.left.equalTo(self.textL);
            make.height.mas_equalTo(24);
        }];

        [_grid mas_makeConstraints:^(MASConstraintMaker *make){
            make.top.equalTo(self.moreBtn.mas_bottom).offset(8);
            make.left.equalTo(self.textL);
            make.right.equalTo(self.card).offset(-kPadding);
            make.height.mas_equalTo(0); // 动态更新
        }];

        // Action bar
        _likeBtn=[UIButton buttonWithType:UIButtonTypeSystem];
        [_likeBtn setTitle:@" 赞" forState:UIControlStateNormal];
        if (@available(iOS 13.0, *)) {
            [_likeBtn setImage:[UIImage systemImageNamed:@"hand.thumbsup"] forState:UIControlStateNormal];
            [_likeBtn setImage:[UIImage systemImageNamed:@"hand.thumbsup.fill"] forState:UIControlStateSelected];
        }
        _likeBtn.titleLabel.font=[UIFont systemFontOfSize:14];
        [_likeBtn addTarget:self action:@selector(tapLike) forControlEvents:UIControlEventTouchUpInside];

        _cmtBtn=[UIButton buttonWithType:UIButtonTypeSystem];
        [_cmtBtn setTitle:@" 评论" forState:UIControlStateNormal];
        if (@available(iOS 13.0, *)) {
            [_cmtBtn setImage:[UIImage systemImageNamed:@"text.bubble"] forState:UIControlStateNormal];
        }
        _cmtBtn.titleLabel.font=[UIFont systemFontOfSize:14];
        [_cmtBtn addTarget:self action:@selector(tapComment) forControlEvents:UIControlEventTouchUpInside];

        _likesCountL=[UILabel new];
        _likesCountL.font=[UIFont systemFontOfSize:13];
        _likesCountL.textColor=UIColor.secondaryLabelColor;

        UIStackView *actionBar = [[UIStackView alloc] initWithArrangedSubviews:@[_likeBtn, _cmtBtn, UIView.new, _likesCountL]];
        actionBar.axis = UILayoutConstraintAxisHorizontal;
        actionBar.spacing = 12;
        actionBar.alignment = UIStackViewAlignmentCenter;
        [_card addSubview:actionBar];
        [actionBar mas_makeConstraints:^(MASConstraintMaker *make){
            make.top.equalTo(self.grid.mas_bottom).offset(8);
            make.left.equalTo(self.card).offset(kPadding);
            make.right.equalTo(self.card).offset(-kPadding);
            make.height.mas_equalTo(kActionBarH);
        }];

        // Comments stack
        _commentsStack = [[UIStackView alloc] init];
        _commentsStack.axis = UILayoutConstraintAxisVertical;
        _commentsStack.spacing = 6;
        [_card addSubview:_commentsStack];
        [_commentsStack mas_makeConstraints:^(MASConstraintMaker *make){
            make.top.equalTo(actionBar.mas_bottom).offset(6);
            make.left.equalTo(self.card).offset(kPadding);
            make.right.equalTo(self.card).offset(-kPadding);
            make.bottom.equalTo(self.card).offset(-kPadding-0.5);
        }];

        // Ultra-thin hairline
        _hairline = [UIView new];
        _hairline.backgroundColor = [UIColor colorWithWhite:0 alpha:0.06];
        [self.contentView addSubview:_hairline];
        [_hairline mas_makeConstraints:^(MASConstraintMaker *make){
            make.left.equalTo(self.contentView).offset(kPadding);
            make.right.equalTo(self.contentView).offset(-kPadding);
            make.bottom.equalTo(self.contentView);
            make.height.mas_equalTo(0.5);
        }];
    }
    return self;
}

- (void)tapAvatar {
    if ([self.delegate respondsToSelector:@selector(momentCellDidTapAvatar:)]) {
        [self.delegate momentCellDidTapAvatar:self.momentId];
    }
}


- (void)layoutSubviews {
    [super layoutSubviews];
    // 告诉 Auto Layout 文本有效宽度，保证多行计算正确
    CGFloat cardW = self.contentView.bounds.size.width - kPadding*2;
    CGFloat textW = cardW - kPadding*2;
    if (fabs(self.textL.preferredMaxLayoutWidth - textW) > 0.5) {
        self.textL.preferredMaxLayoutWidth = textW;
        [self.contentView setNeedsLayout];
        [self.contentView layoutIfNeeded];
    }
}

- (void)prepareForReuse {
    [super prepareForReuse];
    [self.avatar sd_cancelCurrentImageLoad];
    self.avatar.image = nil;
    for (UIView *v in self.grid.subviews) [v removeFromSuperview];
    for (UIView *v in self.commentsStack.arrangedSubviews) {
        [self.commentsStack removeArrangedSubview:v];
        [v removeFromSuperview];
    }
}

- (void)configure:(SMMoment *)m {
    self.momentId = m.momentId;

    // 头像
    NSURL *avatarURL = (m.avatarURL.length ? [NSURL URLWithString:m.avatarURL] : nil);
    UIImage *ph = nil;
    if (@available(iOS 13.0, *)) ph = [UIImage systemImageNamed:@"person.circle"];
    [self.avatar sd_setImageWithURL:avatarURL placeholderImage:ph];

    // 文本、作者、时间
    self.author.text = (m.author && [m.author isKindOfClass:NSString.class]) ? m.author : @"用户";
    self.timeL.text = [SMTimeAgo stringFromDate:m.createdAt];
    NSString *txt = (m.text && [m.text isKindOfClass:NSString.class]) ? m.text : @"";
    self.textL.text = txt;

    // 三行折叠判断
    CGFloat cardW = UIScreen.mainScreen.bounds.size.width - kPadding*2;
    CGFloat textW = cardW - kPadding*2;
    CGFloat lineH = [UIFont systemFontOfSize:15].lineHeight;
    CGFloat max3 = ceil(lineH * kTextMaxLines);
    CGRect full = [txt boundingRectWithSize:CGSizeMake(textW, CGFLOAT_MAX)
                                    options:NSStringDrawingUsesLineFragmentOrigin
                                 attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}
                                    context:nil];
    self.needMoreButton = (ceil(full.size.height) > max3 + 1);
    self.moreBtn.hidden = !self.needMoreButton;
    self.moreBtn.selected = m.isExpanded;
    [self.moreBtn setTitle:(m.isExpanded?@"收起":@"展开") forState:UIControlStateNormal];

    if (m.isExpanded) {
        self.textL.numberOfLines = 0;
        self.textMaxHConstraint.active = NO;
    } else {
        self.textL.numberOfLines = kTextMaxLines;
        self.textMaxHConstraint.constant = max3;
        self.textMaxHConstraint.active = YES;
    }

    // 点赞
    self.likeBtn.selected = m.isLiked;
    self.likesCountL.text = [NSString stringWithFormat:@"%ld",(long)m.likesCount];

    // 9 宫格 & 评论
    [self renderGrid:m.imageURLs];
    [self renderComments:m.comments];
}

#pragma mark - Grid
- (void)renderGrid:(NSArray<NSString *> *)urls {
    for (UIView *v in self.grid.subviews) [v removeFromSuperview];
    NSInteger count = urls.count;
    if (count == 0) {
        [self.grid mas_updateConstraints:^(MASConstraintMaker *make){ make.height.mas_equalTo(0); }];
        return;
    }
    NSInteger cols = 3;
    CGFloat cardW = UIScreen.mainScreen.bounds.size.width - kPadding*2;
    CGFloat contentW = cardW - kPadding*2;
    CGFloat item = floor((contentW - (cols-1)*kGridSpacing)/cols);

    for (NSInteger i=0;i<count;i++){
        NSInteger r = i/cols, c = i%cols;
        UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake((item+kGridSpacing)*c, (item+kGridSpacing)*r, item, item)];
        iv.contentMode = UIViewContentModeScaleAspectFill; iv.clipsToBounds=YES; iv.layer.cornerRadius = 6;
        NSString *u = urls[i];
        UIImage *ph = nil;
        if (@available(iOS 13.0, *)) ph = [UIImage systemImageNamed:@"photo"];
        [iv sd_setImageWithURL:[NSURL URLWithString:u] placeholderImage:ph];
        [self.grid addSubview:iv];
    }
    NSInteger rows = (count+cols-1)/cols;
    CGFloat gridH = rows>0 ? rows*item + (rows-1)*kGridSpacing : 0;
    [self.grid mas_updateConstraints:^(MASConstraintMaker *make){ make.height.mas_equalTo(gridH); }];
}

#pragma mark - Comments
- (void)renderComments:(NSArray<SMComment *> *)comments {
    for (UIView *v in self.commentsStack.arrangedSubviews) {
        [self.commentsStack removeArrangedSubview:v];
        [v removeFromSuperview];
    }
    for (SMComment *c in comments) {
        UIView *bubble = [UIView new];
        bubble.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
        bubble.layer.cornerRadius = 8;

        UILabel *l = [UILabel new];
        l.numberOfLines = kCommentMaxLines;

        NSString *author = (c.author && [c.author isKindOfClass:NSString.class]) ? c.author : @"匿名";
        NSString *txt = (c.text && [c.text isKindOfClass:NSString.class]) ? c.text : @"";
        NSMutableAttributedString *as =
        [[NSMutableAttributedString alloc] initWithString:author
                                               attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14]}];
        if (txt.length) {
            [as appendAttributedString:
             [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@": %@",txt]
                                             attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}]];
        }
        l.attributedText = as;

        [bubble addSubview:l];
        [l mas_makeConstraints:^(MASConstraintMaker *make){
            make.edges.equalTo(bubble).insets(UIEdgeInsetsMake(6, 8, 6, 8));
        }];
        [self.commentsStack addArrangedSubview:bubble];
    }
}

#pragma mark - Actions
- (void)tapLike {
    if ([self.delegate respondsToSelector:@selector(momentCellDidTapLike:)]) {
        [self.delegate momentCellDidTapLike:self.momentId];
    }
}
- (void)tapComment {
    if ([self.delegate respondsToSelector:@selector(momentCellDidTapComment:)]) {
        [self.delegate momentCellDidTapComment:self.momentId];
    }
}
- (void)tapMore {
    if ([self.delegate respondsToSelector:@selector(momentCellDidToggleExpand:)]) {
        [self.delegate momentCellDidToggleExpand:self.momentId];
    }
}

#pragma mark - Height
+ (CGFloat)heightForMoment:(SMMoment *)m width:(CGFloat)width {
    CGFloat cardW = width - kPadding*2;
    CGFloat textW = cardW - kPadding*2;

    NSString *txt = (m.text && [m.text isKindOfClass:NSString.class]) ? m.text : @"";
    CGRect full = [txt boundingRectWithSize:CGSizeMake(textW, CGFLOAT_MAX)
                                    options:NSStringDrawingUsesLineFragmentOrigin
                                 attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];

    CGFloat lineH = [UIFont systemFontOfSize:15].lineHeight;
    CGFloat max3  = ceil(lineH * kTextMaxLines);
    BOOL needMore = (ceil(full.size.height) > max3 + 1);

    CGFloat textH = m.isExpanded ? ceil(full.size.height) : MIN(ceil(full.size.height), max3);
    CGFloat moreH = needMore ? (4 + 24) : 0;

    CGFloat topH = kPadding + kAvatar + 8;

    NSInteger count = m.imageURLs.count, cols = 3;
    CGFloat itemW = floor((textW - (cols-1)*kGridSpacing)/cols);
    NSInteger rows = (count+cols-1)/cols;
    CGFloat gridH = rows>0 ? rows*itemW + (rows-1)*kGridSpacing : 0;

    CGFloat actionH = 8 + kActionBarH + 6;

    CGFloat commentsH = 0;
    for (SMComment *c in m.comments) {
        NSString *author = (c.author && [c.author isKindOfClass:NSString.class]) ? c.author : @"匿名";
        NSString *txt2   = (c.text && [c.text isKindOfClass:NSString.class]) ? c.text : @"";
        NSString *fullT  = [NSString stringWithFormat:@"%@: %@", author, txt2];
        CGRect r = [fullT boundingRectWithSize:CGSizeMake(textW-16, CGFLOAT_MAX)
                                       options:NSStringDrawingUsesLineFragmentOrigin
                                    attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
        CGFloat one = 18.0;
        CGFloat maxH = one * kCommentMaxLines + 12; // + bubble padding
        commentsH += MIN(ceil(r.size.height)+12, maxH) + 6;
    }

    CGFloat bottom = kPadding + 0.5;
    CGFloat total = kPadding + topH + textH + moreH + 8 + gridH + actionH + commentsH + bottom;
    return ceil(total);
}

@end
